package com.zoe.vhr.filter;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zoe.vhr.exception.VerifyCodeException;
import com.zoe.vhr.model.Hr;
import com.zoe.vhr.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/26
 * @Description 支持Json字符串方式登录
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    RedisService redisService;

    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (ObjectUtil.notEqual("POST", request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 判断请求头是不是以application/json
        if (StrUtil.equals(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)
                ||
                StrUtil.equals(request.getContentType(), MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            try (
                    // 获取流
                    ServletInputStream inputStream = request.getInputStream()
            ) {
                // 流操作
                String read = IoUtil.read(inputStream, CharsetUtil.UTF_8);
                Map<String, String> map = JSONUtil.toBean(read, Map.class);

                // checkVerifyCode(map, redisService);


                String username = map.getOrDefault("username", "");
                String password = map.getOrDefault("password", "");

                username = username.trim();
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                this.setDetails(request, authRequest);
                // 手动设置Session,控制Session并发
                Hr hr = new Hr();
                hr.setUsername(username);
                sessionRegistry.registerNewSession(request.getSession(true).getId(), hr);
                return this.getAuthenticationManager().authenticate(authRequest);

            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return super.attemptAuthentication(request, response);
    }


    private void checkVerifyCode(Map<String, String> map, RedisService redisService) {

        String verifyCode = map.getOrDefault("verifyCode", null);

        String uuid = map.getOrDefault("uuid", null);

        String sessionVerifyCode = redisService.getCacheObject(uuid);

        if (ObjectUtil.notEqual(verifyCode, sessionVerifyCode)) {
            throw new VerifyCodeException("验证码不正确");
        }
        redisService.deleteObject(uuid);
    }
}
